import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'dva';
import { Form, Input, Button/*, Tree*/ } from 'antd';
import { Icon } from 'react-fa';
import Tabs from '@/components/Tabs/Tabs';
import Grid from '@/components/Grid';
import Layout from '@/components/Layout';
import Dialog from '@/components/Dialog';
import settings, { getPagination } from '@/settings';
import { check } from '@/services/role';
import { createAction } from '@/utils';
import api from '@/api'

// const { TreeNode } = Tree;

const ModelAuthList = props => {
  const dispatch = useDispatch()

  const [selectedRows, setSelectedRows] = useState([])

  const { 
    params = {},
    list = {}
  } = useSelector(_ => _.$auth)

  const { data, total } = list

  const { effects } = useSelector(_ => _.loading)
  const loading = effects['$auth/fetchList']

  const {
    id: roleId
  } = props

  useEffect(() => {
    dispatch(createAction('$auth/fetchList')());
  }, [dispatch]);

  const handleSubmit = (_, callback) => {
    const ids = selectedRows.map(_ => _.id)
    const _data = data.filter(_ => {
      return ids.indexOf(_.id) > -1
    })
    callback({
      roleId,
      privilegeId: ids
    }, _data);
  };

  props.register(handleSubmit)

  const columns = [
    {
      title: '资源url',
      dataIndex: 'resource',
      width: 200,
    },
    {
      title: '名称',
      dataIndex: 'title',
      width: 200
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 300
    },
  ];
  const handleSelectRows = rows => {
    setSelectedRows(rows)
  };
  const handleSearch = (value, e) => {
    e.preventDefault();
    const pagination = getPagination({
      pageNumber: 1,
    });
    dispatch(createAction('$auth/fetchList')({
      ...params,
      ...pagination,
      [settings.search]: value,
    }));
  };
  const handleGridChange = (oldPagination, sorter) => {
    const pagination = getPagination(oldPagination);
    const payload = {
      ...params,
      ...pagination,
    };

    if (sorter.field) {
      payload.sorter = sorter.field;
      payload.order = sorter.order;
    }

    dispatch(createAction('$auth/fetchList')(payload));
  };
  const handleReload = () => {
    dispatch(createAction('$auth/fetchList')(params));
  };

  const pageNumber = params[settings.pageNumber];

  return (
    <Layout
      toolbar={
        <Form layout="inline">
          <Input.Search placeholder="请输入权限名称" onSearch={handleSearch} />
        </Form>
      }
    >
      <Grid
        selectedRows={selectedRows}
        onSelectRow={handleSelectRows}
        columns={columns}
        data={data}
        loading={loading}
        pagination={{
          pageNumber,
          total,
        }}
        onReload={handleReload}
        onChange={handleGridChange}
      />
    </Layout>
  );
}

const ModelAuthForm = props => {
  const dispatch = useDispatch()

  const [selectedRows, setSelectedRows] = useState([])

  const { 
    params = {},
    list= {}
  } = useSelector(_ => _.role$auth)

  const { data, total } = list

  const { effects } = useSelector(_ => _.loading)
  const loading = effects['role$auth/fetchList']

  const {
    id
  } = props

  useEffect(() => {
    if (id) {
      dispatch(createAction('role$auth/fetchList')({
        id
      }));
    }
  }, [dispatch, id]);

  const columns = [
    {
      title: '资源url',
      dataIndex: 'resource',
      width: 200,
    },
    {
      title: '名称',
      dataIndex: 'title',
      width: 200
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 300
    },
  ];
  const handleSelectRows = rows => {
    setSelectedRows(rows)
  };
  const handleSearch = (value, e) => {
    e.preventDefault();
    const pagination = getPagination({
      pageNumber: 1,
    });
    dispatch(createAction('role$auth/fetchList')({
      ...params,
      ...pagination,
      [settings.search]: value,
      id
    }));
  };
  const handleGridChange = (oldPagination, sorter) => {
    const pagination = getPagination(oldPagination);
    const payload = {
      ...params,
      ...pagination,
      id
    };

    if (sorter.field) {
      payload.sorter = sorter.field;
      payload.order = sorter.order;
    }

    dispatch(createAction('role$auth/fetchList')(payload));
  };
  const handleReload = () => {
    dispatch(createAction('role$auth/fetchList')({
      ...params,
      id
    }));
  };
  const handleAdd = e => {
    Dialog.drawer({
      title: '选择权限',
      width: 720,
      fixed: true,
      effect: true,
      component: props => <ModelAuthList {...props} id={id} />,
      url: api.role_auth_add,
      onOk: data => {
        handleReload();
      },
    });
  };
  const handleRemove = e => {
    Dialog.confirm({
      title: '确认提示',
      content: '确定要删除已选择的权限资源？',
      onOk: async () => {
        await dispatch(createAction('role$auth/delete')({
          id: selectedRows.map(_ => _.id)
        }))
        handleReload();
      },
    });
  };

  const pageNumber = params[settings.pageNumber];

  return (
    <Layout
      toolbar={{
        left: (
          <React.Fragment>
            <Button type="primary" onClick={handleAdd}>
              导入权限
            </Button>
            <Button
              type="danger"
              disabled={selectedRows.length === 0}
              onClick={handleRemove}
            >
              删除
            </Button>
          </React.Fragment>
        ),
        right: (
          <Form layout="inline">
            <Input.Search placeholder="请输入权限名称" onSearch={handleSearch} />
          </Form>
        ),
      }}
    >
      <Grid
        selectedRows={selectedRows}
        onSelectRow={handleSelectRows}
        columns={columns}
        data={data}
        loading={loading}
        pagination={{
          pageNumber,
          total,
        }}
        onReload={handleReload}
        onChange={handleGridChange}
      />
    </Layout>
  );
}

const ModelUserList = props => {
  const dispatch = useDispatch()

  const [selectedRows, setSelectedRows] = useState([])

  const { 
    params = {},
    list = {}
  } = useSelector(_ => _.role$user)

  const { data, total } = list

  const { effects } = useSelector(_ => _.loading)
  const loading = effects['role$user/fetchList']

  const {
    id
  } = props

  useEffect(() => {
    if (id) {
      dispatch(createAction('role$user/fetchList')({
        id
      }));
    }
  }, [dispatch, id]);

  const columns = [
    {
      title: '用户名',
      dataIndex: 'name',
    },
    {
      title: '真实姓名',
      dataIndex: 'title',
      align: 'center',
    },
    // {
    //   title: '所属部门',
    //   dataIndex: 'groupLabel'
    // },
    {
      title: '手机号码',
      dataIndex: 'currentMobile',
      align: 'center',
    }
  ];
  const handleSelectRows = rows => {
    setSelectedRows(rows)
  };
  const handleSearch = (value, e) => {
    e.preventDefault();
    const pagination = getPagination({
      pageNumber: 1,
    });
    dispatch(createAction('role$user/fetchList')({
      ...params,
      ...pagination,
      [settings.search]: value,
      id
    }));
  };
  const handleGridChange = (oldPagination, sorter) => {
    const pagination = getPagination(oldPagination);
    const payload = {
      ...params,
      ...pagination,
      id
    };

    if (sorter.field) {
      payload.sorter = sorter.field;
      payload.order = sorter.order;
    }

    dispatch(createAction('role$user/fetchList')(payload));
  };
  const handleReload = () => {
    dispatch(createAction('role$user/fetchList')({
      ...params,
      id
    }));
  };

  const pageNumber = params[settings.pageNumber];

  return (
    <Layout
      toolbar={{
        right: (
          <Form layout="inline">
            <Input.Search placeholder="请输入权限名称" onSearch={handleSearch} />
          </Form>
        ),
      }}
    >
      <Grid
        selectedRows={selectedRows}
        onSelectRow={handleSelectRows}
        columns={columns}
        data={data}
        loading={loading}
        pagination={{
          pageNumber,
          total,
        }}
        onReload={handleReload}
        onChange={handleGridChange}
      />
    </Layout>
  );
}

const ModelForm = Form.create()(props => {
  const dispatch = useDispatch()
  
  const [activeKey, setActiveKey] = useState("1")
  const [selectedRows, setSelectedRows] = useState([])
  
  const { 
    data = {}
  } = useSelector(_ => _.role)
  const { 
    params = {},
    list = {}
  } = useSelector(_ => _.role$auth)

  const { effects } = useSelector(_ => _.loading)
  const loading = effects['role$auth/fetchList']

  const {
    id,
    form: { validateFields, getFieldDecorator }
  } = props

  useEffect(() => {
    if (id) {
      dispatch(createAction('role/fetchOne')({
        id
      }));
      dispatch(createAction('role$auth/fetchList')({
        id
      }));
    }
  }, [dispatch, id]);

  const handleSubmit = (close, callback) => {
    validateFields((err, values) => {
      if (err) {
        setActiveKey("1")
      } else {
        callback({
          privilegeIds: list.data ? list.data.map(_ => _.id) : null,
          ...values,
        });
      }
    });
  };

  props.register(handleSubmit)

  // handleSubmit = (close, callback) => {
  //   const { form, authIds } = this.props;

  //   form.validateFields((err, values) => {
  //     if (!err) {
  //       callback({
  //         ...values,
  //         authIds: authIds.map(_ => Number(_)),
  //       });
  //     }
  //   });
  // };
  // renderTreeNodes = (data = []) =>
  //   data.map(item => {
  //     if (item.items) {
  //       return (
  //         <TreeNode title={item.text} selectable={false} key={item.id} dataRef={item} icon={<Icon name="folder-open" />}>
  //           {this.renderTreeNodes(item.items)}
  //         </TreeNode>
  //       );
  //     }
  //     return (
  //       <TreeNode {...item} title={item.text} selectable={false} key={item.id} dataRef={item} icon={<Icon name="folder-open" />} />
  //     );
  //   });
  // onCheck = checkedKeys => {
  //   const { dispatch } = this.props;
  //   dispatch(createAction('role/updateState')({
  //     authIds: checkedKeys
  //   }));
  // };
  // onSelect = selectedKeys => {
  //   const { dispatch } = this.props;
  //   dispatch(createAction('role/updateState')({
  //     authIds: selectedKeys
  //   }));
  // };
  const columns = [
    {
      title: '资源url',
      dataIndex: 'resource',
      width: 200,
    },
    {
      title: '名称',
      dataIndex: 'title',
      width: 200
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 300
    },
  ];
  const handleSelectRows = rows => {
    setSelectedRows(rows)
  };
  const handleSearch = (value, e) => {
    e.preventDefault();
    const pagination = getPagination({
      pageNumber: 1,
    });
    dispatch(createAction('role$auth/fetchList')({
      ...params,
      ...pagination,
      [settings.search]: value,
    }));
  };
  const handleGridChange = (oldPagination, sorter) => {
    const pagination = getPagination(oldPagination);
    const payload = {
      ...params,
      ...pagination,
    };

    if (sorter.field) {
      payload.sorter = sorter.field;
      payload.order = sorter.order;
    }

    dispatch(createAction('role$auth/fetchList')(payload));
  };
  const handleReload = () => {
    dispatch(createAction('role$auth/fetchList')(params));
  };
  const handleAdd = e => {
    if (id === undefined) {
      Dialog.drawer({
        title: '选择权限',
        width: 720,
        fixed: true,
        effect: true,
        component: ModelAuthList,
        onOk: ({ resolve }, ids, data) => {
          const oldData = list.data || []
          const newData = data || []
          const oldIds = oldData.map(_ => _.id)
          
          const _data = [].concat(oldData, newData.filter(_ => oldIds.indexOf(_.id) === -1))
          dispatch(createAction('role$auth/updateState')({
            list: {
              ...list,
              data: _data
            }
          }))
          resolve()
        }
      });
    } else {
      Dialog.drawer({
        title: '选择权限',
        width: 720,
        fixed: true,
        effect: true,
        component: props => <ModelAuthList {...props} id={id} />,
        url: api.role_auth_add,
        onOk: (data) => {
          handleReload();
        }
      });
    }
  };
  const handleRemove = e => {
    Dialog.confirm({
      title: '确认提示',
      content: '确定要删除已选择的权限资源？',
      onOk: async () => {
        const ids = selectedRows.map(_ => _.id)
        if (id) {
          await dispatch(createAction('role$auth/delete')({
            id: ids
          }))
          handleReload();
        } else {
          const _data = list.data.filter(_ => ids.indexOf(_.id) === -1)
          setSelectedRows(selectedRows.filter(_ => ids.indexOf(_.id) === -1))
          dispatch(createAction('role$auth/updateState')({
            list: {
              ...list,
              data: _data
            }
          }))
        }
      },
    });
  };
  const onChange = activeKey => {
    setActiveKey(activeKey)
  }

  const pageNumber = params[settings.pageNumber];

  return (
    <Tabs activeKey={activeKey} layout="fixed" onChange={onChange}>
      <Tabs.TabPane tab="角色信息" key="1">
        <Form layout="vertical">
          <Form.Item label="角色名称">
            {getFieldDecorator('name', {
              rules: [
                {
                  required: true,
                  message: '请输入角色名称',
                },
                {
                  validator: async (rule, value, callback) => {
                    if (!value || value.trim() === '' || (data.name && data.name.trim() === value.trim())) return callback()
                    const invalid = await check({
                      [settings.valid]: value,
                    })
                    invalid ? callback('角色名称已存在') : callback();
                  },
                },
              ],
              initialValue: data.name,
            })(<Input placeholder="请输入角色名称" disabled={id != null} />)}
          </Form.Item>
          <Form.Item label="角色描述">
            {getFieldDecorator('title', {
              rules: [
                {
                  required: true,
                  message: '请输入角色描述',
                },
              ],
              initialValue: data.title,
            })(<Input placeholder="请输入角色描述" />)}
          </Form.Item>
          <Form.Item label="备注">
            {getFieldDecorator('desc', {
              // rules: [{ message: '请输入备注信息！', min: 5 }],
              initialValue: data.desc,
            })(<Input.TextArea rows={8} placeholder="请输入备注信息" />)}
          </Form.Item>
        </Form>
      </Tabs.TabPane>
      <Tabs.TabPane tab="权限列表" key="2">
        {/*<Tree
          checkable
          multiple
          showIcon
          defaultExpandAll
          checkedKeys={checkedKeys}
          // selectedKeys={selectedKeys}
          // checkStrictly
          rowKey={record => record.id}
          onCheck={this.onCheck}
          onSelect={this.onSelect}
        >
          {this.renderTreeNodes(modules)}
        </Tree>*/}
        <Layout
          toolbar={{
            left: (
              <React.Fragment>
                <Button type="primary" onClick={handleAdd}>
                  导入权限
                </Button>
                <Button
                  type="danger"
                  disabled={selectedRows.length === 0}
                  onClick={handleRemove}
                >
                  删除
                </Button>
              </React.Fragment>
            ),
            right: (
              <Form layout="inline">
                <Input.Search placeholder="请输入权限名称" onSearch={handleSearch} />
              </Form>
            ),
          }}
        >
          <Grid
            selectedRows={selectedRows}
            onSelectRow={handleSelectRows}
            columns={columns}
            data={list.data}
            loading={loading}
            pagination={{
              pageNumber,
              total: list.total,
            }}
            onReload={handleReload}
            onChange={handleGridChange}
          />
        </Layout>
      </Tabs.TabPane>
    </Tabs>
  );
})

const RolePage = props => {
  const dispatch = useDispatch()
  const [selectedRows, setSelectedRows] = useState([])
  const { list = {}, params = {} } = useSelector(_ => _.role)
  const { data, total } = list
  const { effects } = useSelector(_ => _.loading)
  const loading = effects['role/fetchList']

  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      width: 200,
    },
    {
      title: '描述',
      dataIndex: 'title',
      width: 200
    },
    {
      title: '备注',
      dataIndex: 'desc',
      width: 300
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 200,
      align: 'center',
      render: (v, record, index) => {
        return (
          <React.Fragment>
            <span
              className="btn-text" onClick={e => handleMenuEvent(e, 'edit', v)}>
              <Icon
                name="edit"
              />
              编辑
            </span>
            <span
              className="btn-text" onClick={e => handleMenuEvent(e, 'auth', v)}>
              <Icon
                name="lock"
              />
              权限
            </span>
            <span
              className="btn-text" onClick={e => handleMenuEvent(e, 'user', v)}>
              <Icon
                name="user-o"
              />
              用户
            </span>
          </React.Fragment>
        )
      }
    },
  ];
  useEffect(() => {
    dispatch(createAction('role/fetchList')());
  }, [dispatch]);

  const handleMenuEvent = (e, key, id) => {
    e.stopPropagation()

    switch (key) {
      case 'edit':
        handleEdit(e, id)
        break
      case 'auth':
        Dialog.drawer({
          title: '权限管理',
          width: 960,
          component: props => <ModelAuthForm {...props} id={id} />,
          showCancel: false,
          okText: '关闭'
        });
        break
      case 'user':
        Dialog.drawer({
          title: '用户列表',
          width: 960,
          component: props => <ModelUserList {...props} id={id} />,
          showCancel: false,
          okText: '关闭'
        });
        break
      default :
    }
  };

  const handleSelectRows = rows => {
    setSelectedRows(rows)
  };
  const handleAdd = e => {
    dispatch(createAction('role/reset')());
    dispatch(createAction('role$auth/reset')());
    Dialog.open({
      title: '新建角色',
      width: 720,
      fixed: true,
      effect: true,
      component: ModelForm,
      url: api.role_add,
      onOk: data => {
        handleReload();
      },
    });
  };
  const handleEdit = (e, id) => {
    if (id === undefined) {
      id = selectedRows[0].id;
    }
    dispatch(createAction('role/reset')());
    dispatch(createAction('role$auth/reset')());
    Dialog.open({
      title: '修改角色',
      width: 720,
      fixed: true,
      effect: true,
      url: api.role_update,
      data: {
        id,
      },
      // options: {
      //   type: 'put',
      // },
      onOk: data => {
        handleReload();
      },
      component: props => <ModelForm {...props} id={id} />,
      connect: ({ loading }) => ({ loading: loading.effects['role/fetchOne'] }),
    });
  };
  const handleRemove = e => {
    Dialog.confirm({
      title: '确认提示',
      content: '确定要删除已选择的角色？',
      onOk: async () => {
        await dispatch(createAction('role/delete')({
          id: selectedRows.map(_ => _.id)
        }))
        handleReload();
      },
    });
  };
  const handleGridChange = (oldPagination, sorter) => {
    const pagination = getPagination(oldPagination);
    const payload = {
      ...params,
      ...pagination,
    };

    if (sorter.field) {
      payload.sorter = sorter.field;
      payload.order = sorter.order;
    }

    dispatch(createAction('role/fetchList')(payload));
  };
  const handleReload = () => {
    dispatch(createAction('role/fetchList')(params));
  };
  const handleSearch = (value, e) => {
    e.preventDefault();
    const pagination = getPagination({
      pageNumber: 1,
    });
    dispatch(createAction('role/fetchList')({
      ...params,
      ...pagination,
      [settings.search]: value,
    }));
  };

  const pageNumber = params[settings.pageNumber];
  return (
    <Layout
      header={{
        icon: 'user-circle-o',
        title: '角色管理',
      }}
      toolbar={{
        left: (
          <React.Fragment>
            <Button type="primary" onClick={handleAdd}>
              新建
            </Button>
            <Button onClick={handleEdit} disabled={selectedRows.length !== 1}>
              编辑
            </Button>
            <Button
              type="danger"
              disabled={selectedRows.length === 0}
              onClick={handleRemove}
            >
              删除
            </Button>
          </React.Fragment>
        ),
        right: (
          <Form layout="inline">
            <Input.Search placeholder="请输入角色名称或描述" onSearch={handleSearch} />
          </Form>
        ),
      }}
    >
      <Grid
        selectedRows={selectedRows}
        onSelectRow={handleSelectRows}
        columns={columns}
        data={data}
        loading={loading}
        pagination={{
          pageNumber,
          total,
        }}
        onReload={handleReload}
        onChange={handleGridChange}
      />
    </Layout>
  );
}

export default RolePage;
